﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MadeInPortugal;
using MadeInPortugal.Class;
using System.Data;
using System.IO;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace MadeInPortugalWebApplication.WebControl
{
    public partial class ProductWC : System.Web.UI.UserControl
    {
        int editId = 0;
        public int EditId
        {
            get { return editId; }
            set { editId = value; }
        }


        public bool Admin
        {
            get;
            set;
        }
        //Admin = false;
        byte[] UploadedImage;
        int UserId = 0;
        String UserType;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckUser();

                EnableAdminFields();

                fillTypeDropdown();
                FillTagDropDown();
                FillProperties();


                if (EditId != 0)
                {
                    Product prod = new Product();
                    prod = prod.GetById(editId);
                    lblId.Text = editId.ToString();
                    Session["Product"] = prod;
                    tbxName.Text = prod.ProductName;
                    tbxMinReq.Text = prod.MinReq.ToString();
                    tbxPrice.Text = prod.Price.ToString();
                    tbxSpecification.Text = prod.Specifications;
                    //ddlType.Items.FindByValue(prod.Tag.Type[0].ID.ToString()).Selected = true;
                    ddlType.SelectedValue = prod.Tag.Type[0].ID.ToString();
                    FillTagDropDown();
                    ddlTag.Items.FindByValue(prod.Tag.ID.ToString()).Selected = true;
                    ImageUploaded.ImageUrl = HttpContext.Current.Request.Url.Host.ToString() + "\\style\\img\\bigIcons\\" + prod.Id.ToString() + ".image";
                    btnCreate.Text = "Update";
                    //InsertImage(prod);
                    //HttpContext context = new HttpContext(Page.Request,Page.Response);

                    //GetImage(prod, context);
                    cbxProperties.Items.Clear();
                    foreach (ProdProperties item in prod.Properties)
                    {
                        cbxProperties.Items.Add(new ListItem(item.PropertyName, item.PropertyId.ToString(), true));
                        cbxProperties.Items.FindByValue(item.PropertyId.ToString()).Selected = (bool)item.Property;
                    }

                    if (UserType == "Admin")
                    {
                        tbxPriorityDate.Text = prod.PriorityEndDate.ToShortDateString();
                        tbxPriorityBase.Text = prod.Priority.ToString();
                        tbxPriorityFinal.Text = prod.PriorityFinal.ToString();
                    }

                }
                else
                {
                    FillTagDropDown();
                }

            }

        }

        private void CheckUser()
        {
            if (Session["UserType"] == null)
                Response.Redirect("index.aspx");
            if (Session["UserId"] == null)
                Response.Redirect("index.aspx");
            UserType = Session["UserType"].ToString();
            UserId = int.Parse(Session["UserId"].ToString());
        }

        private void EnableAdminFields()
        {
            if (UserType == "Admin")
            {
                trPriority.Visible = true;
                trPriorityFinal.Visible = true;
                trPriorityDate.Visible = true;
            }
            else
            {
                trPriority.Visible = false;
                trPriorityFinal.Visible = false;
                trPriorityDate.Visible = false;
            }
        }


        protected void fillTypeDropdown()
        {
            ddlType.Items.Clear();
            ProductType type = new ProductType();
            ProductType[] typeList = type.GetAllType();
            foreach (ProductType item in typeList)
            {
                ddlType.Items.Add(new ListItem(item.Type, item.ID.ToString()));
            }

        }

        private void FillTagDropDown()
        {
            ddlTag.Items.Clear();
            Tag type = new Tag();
            Tag[] typeList = type.GetTagByTypeId(int.Parse(ddlType.SelectedValue));
            foreach (Tag item in typeList)
            {
                ddlTag.Items.Add(new ListItem(item.TagName, item.ID.ToString()));
            }
        }

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillTagDropDown();
        }
        protected void ddlTag_SelectedIndexChanged(object sender, EventArgs e)
        {

            FillProperties();
        }

        private void FillProperties()
        {
            GeneralProperties Properties = new GeneralProperties();
            GeneralProperties[] properties = Properties.GetProperties(int.Parse(ddlTag.SelectedValue));

            cbxProperties.Items.Clear();
            foreach (GeneralProperties item in properties)
            {
                cbxProperties.Items.Add(new ListItem(item.PropertyName, item.ID.ToString()));
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            Product Prod = new Product();
            UploadedImage = fuImage.FileBytes;
            if (Session["Product"] != null)
            {
                Prod = (Product)Session["Product"];
            }
            
            if (fuImage.HasFile)
                Prod.Image = new ProductImage() { Image = UploadedImage, Description = tbxName.Text };
            if (tbxMinReq.Text != "")
                Prod.MinReq = int.Parse(tbxMinReq.Text);
            if (tbxPrice.Text != "")
                Prod.Price = decimal.Parse(tbxPrice.Text);
            Prod.ProductName = tbxName.Text;
            Prod.Specifications = tbxSpecification.Text;
            Prod.Priority = 10;
            Prod.PriorityEndDate = DateTime.Now;
            Random rand = new Random();
            Prod.PriorityFinal = rand.Next() * Prod.Priority;
            Prod.Tag = new Tag() { ID = int.Parse(ddlTag.SelectedItem.Value), TagName = ddlTag.SelectedItem.Text };
            ArrayList propertiesList = new ArrayList();

            for (int i = 0; i < cbxProperties.Items.Count; i++)
            {
                propertiesList.Add(new ProdProperties()
                {
                    PropertyName = cbxProperties.Items[i].Text,
                    GeneralPropertiesId = int.Parse(cbxProperties.Items[i].Value),
                    Property = cbxProperties.Items[i].Selected,
                    Language = ddlLanguage.SelectedItem.Text
                });
            }
            Prod.Properties = (ProdProperties[])propertiesList.ToArray(typeof(ProdProperties));
            if (btnCreate.Text != "Update")
            {
                
                Prod.Enterprise = new Enterprise() { Id = (int.Parse(Session["UserId"].ToString())) };

                Prod = Prod.insert(Prod);
                Page.Response.Redirect("Item.aspx?Id=" + Prod.Id);
            }
            else
            {
                Prod.Id = editId;
                Prod.update(Prod);
            }
        }



        protected void Button1_Click(object sender, EventArgs e)
        {
            UploadedImage = fuImage.FileBytes;

            if (fuImage.HasFile)
            {
                try
                {
                    if (fuImage.PostedFile.ContentType == "image/jpeg")
                    {
                        if (fuImage.PostedFile.ContentLength < 1024000)
                        {
                            string filename = Path.GetFileName(fuImage.FileName);
                            string imageSavePath = Server.MapPath("/images/") + filename;
                            string path = HttpContext.Current.Request.Url.AbsoluteUri;

                            fuImage.SaveAs(imageSavePath);
                            ImageUploaded.ImageUrl = "/images/" + filename;
                            ImageUploaded.Visible = true;
                            //imageUpload1.DataBind();
                            //Label1.Text = "File uploaded.";
                            //Response.AppendHeader("Refresh", "0;URL=" + path);
                        }

                    }
                }
                catch (Exception ex)
                {
                    //Label1.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }
            else
            {
                //Label1.Text = "No File !!!";
            }
        }

        #region Resize Image
        /// <summary>
        /// Resizes a image
        /// </summary>
        /// <param name="fl"></param>
        /// <returns>MemoryStream Image</returns>
        public static MemoryStream ResizeImg(MemoryStream fl)
        {
            int width = 2480;
            int height = 3508;
            int newWidth;
            int newHeight;
            int quality = 40;

            // Create a bitmap of the content of the fileUpload control in memory
            Bitmap originalBMP = new Bitmap(fl);

            // Calculate the new image dimensions
            int origWidth = originalBMP.Width;
            int origHeight = originalBMP.Height;
            int sngRatio = origWidth / origHeight;
            if (sngRatio == 0)
            {
                sngRatio = origHeight / origWidth;
                newHeight = height;
                newWidth = newHeight / sngRatio;
            }
            else
            {
                newWidth = width;
                newHeight = newWidth / sngRatio;
            }
            // Create a new bitmap which will hold the previous resized bitmap
            Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);

            // Create a graphic based on the new bitmap
            Graphics oGraphics = Graphics.FromImage(newBMP);
            // Set the properties for the new graphic file
            oGraphics.SmoothingMode = SmoothingMode.HighQuality;
            oGraphics.InterpolationMode = InterpolationMode.Bicubic;

            // Draw the new graphic based on the resized bitmap
            oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);

            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            // Jpeg image codec
            ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;


            MemoryStream memStream = new MemoryStream();

            newBMP.Save(memStream, jpegCodec, encoderParams);
            memStream.Seek(0, SeekOrigin.Begin);
            return memStream;

        }

        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
        #endregion
    }
}


